
var express = require("express");
var app = express();
var server = require("http").createServer(app);
var BigNumber = require('bignumber.js');
var Web3 = require("web3");
var contract = require("truffle-contract");

app.use(express.static("public"));

// allow origin
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
});

app.get("/", function(req, res){
    res.send('Hello World');
});

var basedata_artifacts = require("../build/contracts/OsGameLogic.json");
var OsBaseData = contract(basedata_artifacts);

let config_artifacts = require("../build/contracts/OsGameConfig.json");
let GameConfig = contract(config_artifacts);

var accounts;
var account;
var web3js;
var meta;
let seller;

let Config;

// init
if (typeof web3js !== 'undefined') {
    web3js = new Web3(web3.currentProvider);
} else {
    web3js = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:9545"));
}

web3js.eth.getAccounts(function(err, accs) {
    if (err != null) {
      console.log("There was an error fetching your accounts.");
      return;
    }

    if (accs.length == 0) {
      console.log("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      return;
    }

    accounts = accs;
    account = accounts[0];
    seller = accounts[5];
    console.log("account = ", account, "seller =", seller);

    // var balance = web3js.eth.getBalance(account);
    // console.log(balance.valueOf()); // instanceof BigNumber
});

var OsBaseDataAddress = "0xaa588d3737b611bafd7bd713445b314bd453a5c8";
OsBaseData.setProvider(web3js.currentProvider);
GameConfig.setProvider(web3js.currentProvider);
OsBaseData.deployed().then(function(instance) {
    meta = instance;
    console.log("instance =", instance.address);

    meta.Transfer(function(err, logs){
        console.log("[Transfer] event =", logs);
      });

      meta.PlayerCreate(function(err, logs){
        console.log("[PlayerCreate] event =", logs);
      });

      meta.ItemCreated(function(err, logs){
        console.log("[ItemCreated] index =", logs.args.index.valueOf(),"itemId =", logs.args.tokenId.valueOf());
      });

      meta.ItemDestroyed(function(err, logs){
        console.log("[ItemDestroyed] index =", logs.args.index.valueOf(),"itemId =", logs.args.tokenId.valueOf());
      });

      meta.AdventureSucc(function(err, logs){
        console.log("[AdventureSucc] event itemId =", logs.args.itemId.valueOf());
        return;
      });

      meta.PropertiesAdd(function(err, logs){
        console.log("[PropertiesAdd] event =", logs.args.it.valueOf());
      });

      meta.SynthesisSucc(function(err, logs){
        console.log("[SynthesisSucc] event itemId =", logs.args.itemId.valueOf());
      });

      meta.setValid.sendTransaction("true", {from:account}).then(function(value){
        console.log("[set valid] value =", value);
    }).catch(function(e) {

    });

    let productId;
    GameConfig.deployed().then(function(addr){
        Config = addr;
        console.log("[GameConfig] address = ", Config.address);
        return meta.setConfig.sendTransaction(Config.address, {from:account});
    }).then(function(trans){
        console.log(">>>>>>set game config>>>>>>trans =", trans);
        return instance.createPlayer.sendTransaction(seller, "seller", [100, 100, 100, 100], {from:seller, gas:3000000});
    }).then(function(info){
        console.log("[createPlayer] info =", info);
        return instance.getPlayerInfo.call(seller);
    }).then(function (info) {
        console.log("[getPlayerInfo] info[2][0] =", info[2][0].valueOf());
        return instance.getItemInfo.call( info[2][0] );
    }).then(function (info) {
        productId = info[2];
        console.log("[Oasis::getItemInfo] productId =", productId.valueOf());
        return instance.createOneTrans.sendTransaction(seller, productId, 1000, {from:seller, gas:3000000});
    }).then(function () {
        return instance.getAllTransactions.call();
    }).then(function (list) {
        console.log("[Oasis::getAllTransactions] list =", list);
    }).catch(function(e){
        
    });
});

// 获取账户
app.get("/getAccount", function(req, res){
    console.log("get account");
    var jsonObj = {"account": account};
    res.send(JSON.stringify(jsonObj));
});

// 创建角色
app.get("/createPlayer", function(req, res){
    var nick = req.query.nick;

    console.log("createPlayer = " + req.query.attibutes);
    var attibutes = JSON.parse(req.query.attibutes);
    console.log("attibutes.power = " + attibutes.power);

    meta.createPlayer.sendTransaction(account, nick,
        [attibutes.power, attibutes.strength, attibutes.wit, attibutes.luck], {from: account, gas:3000000}).then(function(value){
            console.log(">>>>>>value =", value);
        }).catch(function(e) {});
    
    res.send("success");
});

// 获取玩家信息
app.get("/getPlayerInfo", function(req, res){

    return meta.getPlayerInfo.call(account).then(function(info) {
        var playerInfo = {
            "valid": info[0],
            "name": info[1],
            "store": info[2],
            "power": info[3],
            "strength": info[4],
            "wit": info[5],
            "luck": info[6]
        };

        res.send(JSON.stringify(playerInfo));
        console.log("playerInfo" + JSON.stringify(playerInfo));
    });
    res.send("error");
});

// 获取物品信息
app.get("/getItemInfo", function(req, res){

    var tokenid = req.query.tokenid;
    return meta.getItemInfo.call(tokenid).then(function(info) {
        var itemInfo = {
            "valid": info[0],
            "locked": info[1],
            "tokenId": info[2],
            "itemId": info[3],
            "useCount": info[4],
            "owner": info[5],
            "power": info[6],
            "strength": info[7],
            "wit": info[8],
            "luck": info[9]
        };
        res.send(JSON.stringify(itemInfo));
        console.log("getItemInfo" + JSON.stringify(itemInfo));
    });
    
    res.send("error");
});

// 创建一个交易
app.get("/createOneTrans", function(req, res){

    var itenId = req.query.itemid;
    meta.createOneTrans.sendTransaction(account, tokenId, 1000, {from: account}).then(function() {
        
    }).catch(function(e) {});
    
    res.send("success");
});

// 获取交易信息
app.get("/getTransactionInfo", function(req, res){

    var transId = req.query.transid;
    return meta.getTransactionInfo.call(transId).then(function(info) {
        var itemInfo = {
            "valid": info[0],
            "seller": info[1],
            "tokenId": info[2],
            "transId": info[3],
            "createTime": info[4],
            "weiValue": info[5],
        };
        res.send(JSON.stringify(itemInfo));
        console.log("getTransactionInfo" + JSON.stringify(itemInfo));
    });
    
    res.send("success");
});

// 购买商品
app.get("/buyProduct", function(req, res){

    var transId = req.query.transid;
    var weiValue = req.query.weiValue
    meta.buyProduct.sendTransaction(account, transId, {from: account, value: weiValue}).then(function() {
        console.log("buyProduct");
    }).catch(function(e) {});
    res.send("success");
});

// 冒险
app.get("/adventure", function(req, res){

    var food = req.query.food;
    var itemList = JSON.parse(req.query.itemList);
    var bagList = itemList.bagList;
    var conditions = itemList.conditions;

    console.log("-----------------------")
    console.log(food);
    console.log(bagList);
    console.log(conditions);

    meta.adventure.sendTransaction(account, food, bagList, conditions, {from: account, gas: 3000000}).then(function() {
        console.log("adventure");
    }).catch(function(e) {});
    
    res.send("success");
});

// 获取冒险信息
app.get("/getAdventureInfo", function(req, res){

    return meta.getAdventureInfo.call(account).then(function(info) {
        var adventureInfo = {
            "valid": info[0],
            "finished": info[1],
            "lastTime": info[2],
            "colddownTime": info[3],
            "bagList": info[4],
            "rewardItem": info[5],
            "synthesisItem": info[6],
        };
        res.send(JSON.stringify(adventureInfo));
        console.log("getAdventureInfo" + JSON.stringify(adventureInfo));
    });
    
    res.send("error");
});

// 获取所有交易信息
app.get("/getAllTransactions", function(req, res){

    return meta.getAllTransactions.call().then(function(list) {
        var transIds = {
            "transIds": list
        };
        res.send(JSON.stringify(transIds));
        console.log("getAllTransactions" + JSON.stringify(transIds));
    });
    
    res.send("error");
});

console.log("server is running!");
server.listen(8977);